<?php

class PostController extends Controller
{
   /**
    * Set layout
   */
   public $layout = '//layouts/cms/main';
   
   /**
	 * action array filter
	 */
   public function filters()
	{
		return array(
         'accessControl', // perform access control for CRUD operations
      );
	}
   
   /**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
   public function accessRules(){
      $rights = Role::getRights($this->id);
      return $rights;
   }
   
   /**
	 * Check login all action
	 */
   public function beforeAction($action){
      if(is_null(Yii::app()->user->id))
         $this->redirect('/admin/default/login');
      else
         return true;
   }
   
   /**
    * Display page index
   */
	public function actionIndex()
	{
	   
      $page = Yii::app()->request->getParam('page',1); // Lấy số trang
      $limit = Yii::app()->request->getParam('limit',10); // Lấy số dòng hiển thị trên grid
      $sidx = isset($_GET['sidx']) ?  $_GET['sidx'] : 'post_date_update'; // Lấy trường cần sắp xếp
      $sord = isset($_GET['sord']) ? $_GET['sord'] : 'DESC'; // Lấy giá trị muốn sắp xếp
      $start = $limit*$page - $limit; // Thứ tự bản ghi bắt đầu lấy
      $rowList = array(10,20,30,50,100);  
      //Biến xác định phiên làm việc của user
      $session_user = md5(time());
      Yii::app()->session['session_user'] = $session_user;  
      $list = array();
      $model = new Post();
      $model->unsetAttributes();
      
      $criteria = new CDbCriteria;
      $criteria->limit = $limit;
      $criteria->offset = $start;
      $criteria->order = $sidx . ' ' . $sord;
      if(isset($_POST['Post'])){ // Nếu người dùng search
         $model->attributes = $_POST['Post'];
         $params = array();
         
         if(isset($_POST['start_date'])){
            $criteria->addCondition("post_date_create >= :start_date", "AND");
            $params[':start_date'] = strtotime(str_replace('/','-',$_POST['start_date']));
         }
         if(isset($_POST['end_date'])){
            $criteria->addCondition("post_date_create <= :end_date", "AND");
            $params[':end_date'] = strtotime(str_replace('/','-',$_POST['end_date'])) + 86400; //Cuối ngày
         }
         if($model->post_title != ''){
            $criteria->addCondition("post_title like :post_title", "AND");
            $params[':post_title'] = '%'.$model->post_title.'%';
         }
            
         if($model->post_prv_id != 0){
            $criteria->addCondition("post_prv_id = :post_prv_id", "AND");
            $params[':post_prv_id'] = $model->post_prv_id;
         }
            
         if($model->post_dis_id != 0){
            $criteria->addCondition("post_dis_id = :post_dis_id", "AND");
            $params[':post_dis_id'] = $model->post_dis_id;
         }
            
         if($model->post_cat_id != 0){
            $criteria->addCondition("post_cat_id = :post_cat_id", "AND");
            $params[':post_cat_id'] = $model->post_cat_id;
         }
         $criteria->params = $params;
      }
      $object = $model->with('district','province','project')->findAll($criteria);
      if(count($object) > 0){
         foreach($object as $item){
            $list[$item->attributes['post_id']] = $item->attributes;
            $list[$item->attributes['post_id']]['dis_name'] = !is_null($item->getRelated('district')) ? $item->getRelated('district')->attributes['dis_name'] : "Chưa rõ";
            $list[$item->attributes['post_id']]['prv_name'] = !is_null($item->getRelated('province')) ? $item->getRelated('province')->attributes['prv_name'] : "Chưa rõ";
            $list[$item->attributes['post_id']]['prj_name'] = !is_null($item->getRelated('project')) ? $item->getRelated('project')->attributes['prj_name'] : "Chưa X.Định";
         }
      }
      $total_record = $model->count($criteria); // Đếm tổng số bản ghi
      if( $total_record >0 ) {
      	$total_pages = ceil($total_record/$limit);
      } else {
      	$total_pages = 0;
      }
      
      //Danh sach tinh thanh
      $list_province = array(0 => '-- Tỉnh/TP --'); // Danh sách các Tỉnh/Tp
      $province = new Province();
      $object = $province->findAll(array(
         'order' => 'prv_order DESC, prv_name ASC',
      ));
      
      //Danh sach danh muc
      $list_category = array();
      $category = new Category();
      $all_cate = $category->getAll();
      $tree_cate = $category->getTree($all_cate);
      
      if(count($object) > 0){
         foreach($object as $item){
            $list_province[$item->attributes['prv_id']] = $item->attributes['prv_name'];
         }
      }
      
      $list_district = array(0 => '-- Quận/Huyện --');
      if($model->post_prv_id > 0){
         $object = District::model()->getAllByPrvID($model->post_prv_id);
         foreach($object as $item){
            $list_district[$item['dis_id']] = $item['dis_name'];
         }
      }
      
      
      $list_project = array(0 => '-- Dự án --');
      if($model->post_prv_id > 0){
         $object = Project::model()->findAllByAttributes(array('prj_dis_id' => $model->post_dis_id));
         foreach($object as $item){
            $list_project[$item['prj_id']] = $item['prj_name'];
         }
      }
      
      $this->render('index',array("model" => $model,
                                  "session_user" => $session_user,
                                  "list" => $list,
                                  "rowList" => $rowList,
                                  "page" => $page,
                                  "start" => $start,
                                  "limit" => $limit,
                                  "total_record" => $total_record,
                                  "total_pages" => $total_pages,
                                  'list_province' => $list_province,
                                  'list_district' => $list_district,
                                  'list_project' => $list_project,
                                  'tree_cate' => $tree_cate,));
	}
   
   /**
    * 
    * Display page create
   */
   public function actionCreate(){
      $model = new Post();
      $PostImage = new PostImage();
      $session_user = md5(time());
      Yii::app()->session['session_user'] = $session_user;
      $action_user = Yii::app()->request->getParam('action_user',''); // Biến xác định user ấn apply hay save
      $message = '';
      if(isset($_POST['Post'])){
         $model->attributes = $_POST['Post'];
         if($model->post_date_create == ''){
            $model->post_date_create = time();
         }else{
           $model->post_date_create = strtotime(str_replace('/','-',$model->post_date_create));
         }
         $model->post_date_update = $model->post_date_create;
         $model->post_use_id = Yii::app()->user->id;
         if($model->validate()){
            if($model->save()){
               $message = "Đăng tin thành công";   
               
               //Upload image
               $images = CUploadedFile::getInstancesByName('PostImage');
               if(isset($images) && count($images)> 0)
                  $i = 0;
                  foreach ($images as $image=>$pic){
                     $i++;
                     //Rename file image
                     $fileName = date('YmdHis',time()).$i;
                     switch($pic->type){
                        case 'image/jpeg':
                           $fileName .= '.jpg';
                           break;
                        case 'image/png':
                           $fileName .='.png';
                           break;
                        default:
                           $fileName .='.gif';
                           break;
                     }
                     $path_to_upload = Yii::getPathOfAlias('webroot').'/uploads/pictures/post/';
                     if ($pic->saveAs($path_to_upload.$fileName,0777)){    
                        //Lay anh dau tien lam anh dai dien
                        if($i == 1){
                           $post = Post::Model()->findByPk($model->post_id);
                           $post->post_avatar = $fileName;
                           $post->save();
                        }
                        
                        //Resize image
                        $simpleImage = new SimpleImage();
                        $simpleImage->load($path_to_upload.$fileName);
                        $simpleImage->resizeToWidth(680);
                        $simpleImage->save($path_to_upload.$fileName);
                        $simpleImage->load($path_to_upload.$fileName);
                        $simpleImage->resizeToWidth(175);
                        $simpleImage->save($path_to_upload.'thumb_'.$fileName);
                        $PostImage->setIsNewRecord(true);
                        $PostImage->post_img = $fileName;
                                                
                        $PostImage->post_id = $model->post_id;
                        if($PostImage->validate())
                           $PostImage->save();
                        else
                        {
                           CVarDumper::dump($PostImage->errors,10,true);
                        }                  
                     }                
                  }
               }
            }
            
            if($action_user == 'save'){
               $this->redirect('/index.php/admin/'.$this->id);
            }
         }
      
      //Danh sach tinh thanh
      $list_province = array(0 => '-- Tỉnh/TP --'); // Danh sách các Tỉnh/Tp
      $province = new Province();
      $object = $province->findAll(array(
         'order' => 'prv_order DESC, prv_name ASC',
      ));
      
      //Danh sach danh muc
      $list_category = array();
      $category = new Category();
      $all_cate = $category->getAll();
      $tree_cate = $category->getTree($all_cate);
      unset($tree_cate[0]);
      
      if(count($object) > 0){
         foreach($object as $item){
            $list_province[$item->attributes['prv_id']] = $item->attributes['prv_name'];
         }
      }
      $this->pageTitle = 'Đăng bài';
      $this->layout = '//layouts/cms/create';
      $this->render('create',array('model'=>$model,
                                    'PostImage' => $PostImage,
                                    'session_user' => $session_user,
                                    'list_province' => $list_province,
                                    'tree_cate' => $tree_cate,
                                    'message' => $message));
   }
   
   /**
    * 
    * Display page edit
   */
   public function actionEdit($id){
      $model  = new Post();
      $model->attributes = $model->findByPk($id)->attributes;
      $PostImage = new PostImage();
      $session_user = md5(time());
      Yii::app()->session['session_user'] = $session_user;
      $action_user = Yii::app()->request->getParam('action_user',''); // Biến xác định user ấn apply hay save
      $message = '';
      if(isset($_POST['Post'])){
         $model = Post::model()->findByPk($id); // Khởi tạo để edit
         $model->attributes = $_POST['Post'];
         if($model->post_date_create == ''){
            $model->post_date_create = time();
         }else{
           $model->post_date_create = strtotime(str_replace('/','-',$model->post_date_create));
         }
         $model->post_use_id = Yii::app()->user->id;
         if($model->validate()){
            if($model->save()){
               $message = "Cập nhật thành công";   
               
               //Upload image
               $images = CUploadedFile::getInstancesByName('PostImage');
               if(isset($images) && count($images)> 0)
                  $i = 0;
                  foreach ($images as $image=>$pic){
                     $i++;
                     //Rename file image
                     $fileName = date('YmdHis',time()).$i;
                     switch($pic->type){
                        case 'image/jpeg':
                           $fileName .= '.jpg';
                           break;
                        case 'image/png':
                           $fileName .='.png';
                           break;
                        default:
                           $fileName .='.gif';
                           break;
                     }
                     $path_to_upload = Yii::getPathOfAlias('webroot').'/uploads/pictures/post/';
                     if ($pic->saveAs($path_to_upload.$fileName,0777)){    
                        //Lay anh dau tien lam anh dai dien
                        if($i == 1){
                           $post = Post::Model()->findByPk($model->post_id);
                           $post->post_avatar = $fileName;
                           $post->save();
                        }
                        
                        //Resize image
                        $simpleImage = new SimpleImage();
                        $simpleImage->load($path_to_upload.$fileName);
                        $simpleImage->resizeToWidth(680);
                        $simpleImage->save($path_to_upload.$fileName);
                        $simpleImage->load($path_to_upload.$fileName);
                        $simpleImage->resizeToWidth(175);
                        $simpleImage->save($path_to_upload.'thumb_'.$fileName);
                        $criteria = new CDbCriteria();
                        $criteria->addCondition('post_id =' . $id);
                        $PostImage->deleteAll($criteria);
                        $PostImage->setIsNewRecord(true);
                        $PostImage->post_img = $fileName;
                                                
                        $PostImage->post_id = $model->post_id;
                        if($PostImage->validate())
                           $PostImage->save();
                        else
                        {
                           CVarDumper::dump($PostImage->errors,10,true);
                        }                  
                     }                
                  }
               }
            }
            
            if($action_user == 'save'){
               $this->redirect('/index.php/admin/'.$this->id);
            }
         }
      
      //Danh sach tinh thanh
      $list_province = array(0 => '-- Tỉnh/TP --'); // Danh sách các Tỉnh/Tp
      $province = new Province();
      $object = $province->findAll(array(
         'order' => 'prv_order DESC, prv_name ASC',
      ));
      
      //Danh sach danh muc
      $list_category = array();
      $category = new Category();
      $all_cate = $category->getAll();
      $tree_cate = $category->getTree($all_cate);
      unset($tree_cate[0]);
      
      if(count($object) > 0){
         foreach($object as $item){
            $list_province[$item->attributes['prv_id']] = $item->attributes['prv_name'];
         }
      }
      $list_distric = array(0 => '-- Quận/Huyện --');
      if($model->post_prv_id){
         $district = new District();
         $object = $district->findAllByAttributes(array('prv_id' => $model->post_prv_id));
         if(count($object) > 0){
            foreach($object as $item){
               $list_distric[$item->attributes['dis_id']] = $item->attributes['dis_name'];
            }
         }
      }
      $list_project = array(0 => '-- Dự án --');
      if($model->post_dis_id > 0){
         $object = Project::model()->findAllByAttributes(array('prj_dis_id' => $model->post_dis_id));
         if(count($object) > 0){
            foreach($object as $item){
               $list_project[$item->attributes['prj_id']] = $item->attributes['prj_name'];
            }
         }
      }
      
      $this->pageTitle = 'Cập nhật bài đăng';
      $this->layout = '//layouts/cms/create';
      $this->render('edit',array('model'=>$model,
                                    'PostImage' => $PostImage,
                                    'session_user' => $session_user,
                                    'list_province' => $list_province,
                                    'list_distric' => $list_distric,
                                    'list_project' => $list_project,
                                    'tree_cate' => $tree_cate,
                                    'message' => $message));
   }
   
   
   /**
    * Deactive record
   */
	public function actionDeactive(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == Yii::app()->session['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'UPDATE post SET post_active = 0 WHERE post_id IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}
   
   /**
    * Refresh record (update post_date_update)
   */
   public function actionRefresh(){
      $id = Yii::app()->request->getParam('id');
      $model = Post::model()->findByPk($id);
      $model->post_use_id = Yii::app()->user->id;
      $model->post_date_update = time();
      $message = '';
      $error = 1;
      if($model->validate()){
         if($model->save()){
            $error = 0;
         }else{
            $error = 1;
         }   
      }
      $message = $model->errors;
      echo json_encode(array('error' => $error,'message' => $message));
   }
   
   /**
    * VIP record 
   */
   public function actionVip(){
      $id = Yii::app()->request->getParam('id');
      $vip = Yii::app()->request->getParam('vip');
      $model = Post::model()->findByPk($id);
      $model->post_use_id = Yii::app()->user->id;
      $model->post_vip = $vip;
      $message = '';
      $error = 1;
      if($model->validate()){
         if($model->save()){
            $error = 0;
         }else{
            $error = 1;
         }   
      }
      $message = $model->errors;
      echo json_encode(array('error' => $error,'message' => $message));
   }
   
   /**
    * Active record
   */
	public function actionActive(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == Yii::app()->session['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'UPDATE post SET post_active = 1 WHERE post_id IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}
   
   /**
    * Delete record
   */
	public function actionDelete(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == Yii::app()->session['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'DELETE FROM post WHERE post_id IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}


	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}